import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import {
  Video,
  Link as LinkIcon,
  Store,
  Upload,
  CheckCircle,
} from "lucide-react";
import { useToast, showError } from "@/hooks/use-toast";

import { addAnalysis } from "@/api/VideoAnalysis";
import { getSocialList, syncFlow } from "@/api/social";

const VideoEntry = () => {
  const [platform, setPlatform] = useState("TikTok");
  const [language, setLanguage] = useState("zh-CN");
  const [links, setLinks] = useState("");
  const [thirdPartyPlatform, setThirdPartyPlatform] = useState("fastmous");
  const [inputType, setInputType] = useState("product");
  const [thirdPartyLink, setThirdPartyLink] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const { toast } = useToast();

  const handleManualSubmit = async () => {
    if (
      !links.startsWith("https://www.tiktok.com") &&
      !links.startsWith("https://www.instagram.com") &&
      !links.startsWith("https://www.youtube.com") &&
      !links.startsWith("/profile")
    ) {
      showError("请输入有效的视频", "请输入视频链接");
      return;
    }

    setIsLoading(true);
    const resdata = await addAnalysis(links, language);
    const { code } = resdata;
    if (code == 200) {
      toast({
        title: "提交成功",
        description: `提交成功，等到解析中`,
        action: (
          <Button
            variant="outline"
            size="sm"
            onClick={() => (window.location.href = "/library")}
          >
            查看详情
          </Button>
        ),
      });
      setLinks("");
    }
    setIsLoading(false);
  };

  const setThirdPartyPlatformDom = (e: string) => {
    setThirdPartyPlatform(e);
    if (e == "shoplus") {
      setInputType("product");
    }
  };

  const handleThirdPartySubmit = async () => {
    if (!thirdPartyLink.trim()) {
      toast({
        variant: "destructive",
        title: "请输入链接",
        description: "请输入商品或店铺链接",
      });
      return;
    }

    setIsLoading(true);
    const resData = await syncFlow(
      thirdPartyLink,
      thirdPartyPlatform,
      inputType
    );
    console.info(resData);
    setIsLoading(false);
    toast({
      title: "提交成功",
      description: `已提交收集，请等待数据收集`,
    });
  };

  return (
    <div className="container mx-auto py-8 px-4">
      <div className="text-center mb-8">
        <h1 className="text-3xl font-bold mb-3 bg-[var(--gradient-hero)] bg-clip-text text-transparent">
          视频录入
        </h1>
        <p className="text-muted-foreground text-lg">
          输入视频链接，开始智能分析和脚本处理
        </p>
      </div>

      <Tabs defaultValue="manual" className="space-y-6">
        <TabsList className="grid w-full grid-cols-2 h-12">
          <TabsTrigger value="manual" className="flex items-center gap-2">
            <LinkIcon className="h-4 w-4" />
            手动输入链接
          </TabsTrigger>
          <TabsTrigger value="third-party" className="flex items-center gap-2">
            <Store className="h-4 w-4" />
            第三方平台收集
          </TabsTrigger>
        </TabsList>

        <TabsContent value="manual">
          <Card className="shadow-[var(--shadow-card)] border-0">
            <CardHeader className="bg-[var(--gradient-secondary)] rounded-t-lg">
              <CardTitle className="flex items-center gap-2">
                <Video className="h-5 w-5 text-primary" />
                手动输入视频链接
              </CardTitle>
              <CardDescription>支持输入视频链接进行分析</CardDescription>
            </CardHeader>
            <CardContent className="space-y-6 pt-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="platform">视频平台</Label>
                  <Select value={platform} onValueChange={setPlatform}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择平台" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="TikTok">TikTok</SelectItem>
                      {/* <SelectItem value="Instagram">Instagram</SelectItem>
                      <SelectItem value="Youtube">YouTube</SelectItem> */}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="language">译文语言</Label>
                  <Select value={language} onValueChange={setLanguage}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择语言" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="zh-CN">中文（简）</SelectItem>
                      <SelectItem value="zh-TW">中文（繁）</SelectItem>
                      <SelectItem value="en">English</SelectItem>
                      <SelectItem value="ja">日本語</SelectItem>
                      <SelectItem value="ko">한국어</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="links">视频链接</Label>
                <Textarea
                  id="links"
                  placeholder="请输入视频链接，多个链接请换行分隔&#10;&#10;例如：&#10;https://www.tiktok.com/@user/video/123456&#10;https://www.tiktok.com/@user/video/789012"
                  value={links}
                  onChange={(e) => setLinks(e.target.value)}
                  rows={6}
                  className="resize-none"
                />
                <div className="flex items-center justify-between text-sm text-muted-foreground">
                  <span>
                    {links
                      ? `已输入 ${
                          links.split("\n").filter((link) => link.trim()).length
                        } 个链接`
                      : "暂未输入链接"}
                  </span>
                  <Badge variant="secondary">{platform}</Badge>
                </div>
              </div>

              <Button
                onClick={handleManualSubmit}
                disabled={isLoading || !links.trim()}
                variant="hero"
                size="lg"
                className="w-full"
              >
                {isLoading ? (
                  <>
                    <Upload className="h-4 w-4 mr-2 animate-spin" />
                    正在分析中...
                  </>
                ) : (
                  <>
                    <CheckCircle className="h-4 w-4 mr-2" />
                    确认提交
                  </>
                )}
              </Button>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="third-party">
          <Card className="shadow-[var(--shadow-card)] border-0">
            <CardHeader className="bg-[var(--gradient-secondary)] rounded-t-lg">
              <CardTitle className="flex items-center gap-2">
                <Store className="h-5 w-5 text-primary" />
                第三方平台收集
              </CardTitle>
              <CardDescription>从电商平台自动收集相关视频内容</CardDescription>
            </CardHeader>
            <CardContent className="space-y-6 pt-6">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="thirdPartyPlatform">第三方平台</Label>
                  <Select
                    value={thirdPartyPlatform}
                    onValueChange={(e) => setThirdPartyPlatformDom(e)}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择平台" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="fastmous">Fastmoss</SelectItem>
                      <SelectItem value="shoplus">超店</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="inputType">链接类型</Label>
                  <Select value={inputType} onValueChange={setInputType}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择类型" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="product">商品链接</SelectItem>
                      {thirdPartyPlatform == "fastmous" ? (
                        <SelectItem value="store">店铺链接</SelectItem>
                      ) : (
                        ""
                      )}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="language">译文语言</Label>
                  <Select value={language} onValueChange={setLanguage}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择语言" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="zh-CN">中文（简）</SelectItem>
                      <SelectItem value="zh-TW">中文（繁）</SelectItem>
                      <SelectItem value="en">English</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="thirdPartyLink">
                  {inputType === "product" ? "商品链接" : "店铺链接"}
                </Label>
                <Input
                  id="thirdPartyLink"
                  placeholder={`请输入${
                    inputType === "product" ? "商品" : "店铺"
                  }链接`}
                  value={thirdPartyLink}
                  onChange={(e) => setThirdPartyLink(e.target.value)}
                  className="h-12"
                />
                <div className="flex items-center justify-between text-sm text-muted-foreground">
                  <span>
                    将从 {thirdPartyPlatform} 收集
                    {inputType === "product" ? "商品" : "店铺"}相关视频
                  </span>
                  <Badge variant="secondary">{thirdPartyPlatform}</Badge>
                </div>
              </div>

              <Button
                onClick={handleThirdPartySubmit}
                disabled={isLoading || !thirdPartyLink.trim()}
                variant="hero"
                size="lg"
                className="w-full"
              >
                {isLoading ? (
                  <>
                    <Upload className="h-4 w-4 mr-2 animate-spin" />
                    正在收集中...
                  </>
                ) : (
                  <>
                    <CheckCircle className="h-4 w-4 mr-2" />
                    开始收集
                  </>
                )}
              </Button>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
};

export default VideoEntry;
